package ru.spb.osll.myfit.client.view;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import ru.spb.osll.myfit.client.dialog.ErrorDialog;
import ru.spb.osll.myfit.client.manager.PageExecutingManager;
import ru.spb.osll.myfit.client.service.SuiteExecutingService;
import ru.spb.osll.myfit.client.service.SuiteExecutingServiceAsync;
import ru.spb.osll.myfit.client.widget.ExecutingListener;
import ru.spb.osll.myfit.common.ExecutingResult;
import ru.spb.osll.myfit.common.PageExecutingResult;
import ru.spb.osll.myfit.common.SuiteExecutingResult;

import java.util.List;

public class SuiteResultViewController implements IViewController {
  private final SuiteExecutingServiceAsync m_suiteExecutingService =
          GWT.create(SuiteExecutingService.class);
  private final ErrorDialog m_errorDialog = new ErrorDialog();

  @Override
  public IView getView(String address) {
    final SuiteResultView view = new SuiteResultView();
    final String id = Window.Location.getParameter("id");
    m_suiteExecutingService.getExecutingResult(id, new AsyncCallback<SuiteExecutingResult>() {
      @Override
      public void onFailure(Throwable caught) {
        m_errorDialog.setMessage(caught);
        m_errorDialog.center();
      }

      @Override
      public void onSuccess(final SuiteExecutingResult suiteExecutingResult) {
        if (suiteExecutingResult != null){
          final PageExecutingManager pageExecutingManager = new PageExecutingManager();
          final ExecutingListener pageExecutingListener = new ExecutingListener() {
            @Override
            public void processExecutingResult(ExecutingResult result) {
              view.updateResult(result);
            }

            @Override
            public void finish() {
            }
          };

          m_suiteExecutingService.getPageExecutingResults(id, new AsyncCallback<List<PageExecutingResult>>() {
            @Override
            public void onFailure(Throwable caught) {
              m_errorDialog.setMessage(caught);
              m_errorDialog.center();
            }

            @Override
            public void onSuccess(List<PageExecutingResult> results) {
              for (PageExecutingResult result : results) {
                view.addResultToWidget(result);

                pageExecutingManager.addResultToListen(result);
                pageExecutingManager.addListener(result.getId(), pageExecutingListener);
              }

              view.displayResult(suiteExecutingResult);
            }
          });


        } else {
          m_errorDialog.setMessage("Suite result with id = " + id + " not found");
          m_errorDialog.center();
        }
      }
    });
    return view;
  }
}
